package com.judian.smart.util;

import android.content.Context;
import android.util.Log;

import com.iflytek.cloud.SpeechError;
import com.iflytek.cloud.TextUnderstanderListener;
import com.iflytek.cloud.UnderstanderResult;
import com.judian.smart.base.MyApplication;
import com.judian.smart.model.WeatherData;

import java.util.Arrays;
import java.util.TimerTask;

/**
 * author: Peter
 * date: 2019/10/12 星期六 13:44
 * desc: 天气时间任务栈(防止被系统杀死)
 */
public class WeatherTimeTask {
    private static final String TAG = WeatherTimeTask.class.getSimpleName();
    private Context context = MyApplication.getInstance();
    private TimerUtil timerUtil;
    private static WeatherTimeTask weatherTimeTask;

    private WeatherTimeTask() {
    }

    public static WeatherTimeTask getInstance() {
        if (weatherTimeTask == null) {
            weatherTimeTask = new WeatherTimeTask();
        }
        return weatherTimeTask;
    }

    private void start() {
        timerUtil = new TimerUtil(new TimerTask() {
            @Override
            public void run() {
                Log.d(TAG, "run: ");
                new MyTextUnderstander().understandText("今天广州天气", new TextUnderstanderListener() {
                    @Override
                    public void onResult(UnderstanderResult result) {
                        Log.d(TAG, "onResult: 天气定时查询返回！");
                        String json = result.getResultString();
                        JsonParse jp = new JsonParse(context);
                        WeatherData[] weatherdataarray = jp.WeatherXUnderstander(json);
                        Log.d(TAG, "onResult: weatherdataarray:" + Arrays.toString(weatherdataarray));

                    }

                    @Override
                    public void onError(SpeechError arg0) {
                        Log.d(TAG, "onError: 更新天气失败"
                                + "\n" + "错误码：" + arg0.getErrorCode()
                                + "\n" + "错误描述：" + arg0.getErrorDescription());
                    }
                });
            }
        }, 0);
        timerUtil.scheduleRepeat(0, 2 * 60 * 1000);
    }

    public void restart() {
        if (timerUtil != null) {
            timerUtil.cancel();
        }
        start();
    }

    public void stop() {
        if (timerUtil != null) {
            timerUtil.cancel();
        }
    }
}
